package com.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * NIO源生第一个DEMO，NIOClient客户端
 * @author hcf
 * @email hcf0108@163.com
 * @create 2019-03-06 下午 5:34
 **/
public class NIOClient {
    private static int flag = 1;
    /** 缓冲区大小 */
    private static int blockSize = 4096;
    /** 发送数据缓冲区 */
    private static ByteBuffer sendbuffer = ByteBuffer.allocate(blockSize);
    /** 接受数据缓冲区 */
    private static ByteBuffer receivebuffer = ByteBuffer.allocate(blockSize);
    /** 服务端的端口绑定 */
    private final static InetSocketAddress serverAddress = new InetSocketAddress("127.0.0.1",7080);


    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        // 打开选择器
        Selector selector = Selector.open();
        socketChannel.register(selector,SelectionKey.OP_CONNECT);//注册连接事件
        socketChannel.connect(serverAddress);//发送连接


        //遍历key
        Set<SelectionKey> selectionKeys =null;
        Iterator<SelectionKey> it = null;
        SelectionKey selectionKey = null;
        SocketChannel client = null;
        String receiveText;
        String sendText;
        int count=0;
        while (true) {
            selectionKeys = selector.selectedKeys();
            it = selectionKeys .iterator();
            while (it.hasNext()) {
                selectionKey = it.next();
                if(selectionKey.isConnectable()){//客户端已连接事件
                    System.out.println("client connet");
                    client= (SocketChannel) selectionKey.channel();
                    if(client.isConnectionPending()){//判断是否已连接
                        client.finishConnect();
                        System.out.println("client 已完成连接");
                        //发送数据
                        sendbuffer.clear();
                        sendbuffer.put("Hello Server".getBytes());
                        sendbuffer.flip();
                        count = client.write(sendbuffer);
                    }
                    client.register(selector, SelectionKey.OP_READ);
                }

                if(selectionKey.isReadable()){
                    client = (SocketChannel) selectionKey.channel();
                    receivebuffer.clear();
                    count = client.read(receivebuffer);
                    if(count>0){
                        receiveText = new String(receivebuffer.array(),0,count);
                        System.out.println("客户端接受服务端数据："+receiveText);
                        client.register(selector,SelectionKey.OP_WRITE);
                    }
                }

                if(selectionKey.isWritable()){
                    sendbuffer.clear();
                    client = (SocketChannel) selectionKey.channel();
                    sendText= "msg send to Server: "+ flag++;
                    sendbuffer.put(sendText.getBytes());
                    sendbuffer.flip();
                    client.write(sendbuffer);
                    System.out.println("客户端发送数据给服务端结束");
                    client.register(selector,SelectionKey.OP_READ);

                }
            }
            selectionKeys.clear();
        }


    }
}
